<template lang="pug">
.activity
  .activity-section
    .header
      .header-title
        span 活动图片设置
        label 支持png、jpg格式图片，仅能上传1张，建议尺寸为：996*242
      .header-handle
        el-button(name="primary" size="small" @click="save" v-if="$permission('AB-01003-004')") 应用到平台
    .section-content
      el-upload(
        action="#"
        :multiple="false"
        accept="image/png, image/jpeg, image/jpg, image/gif"
        ref="upload"
        :show-file-list="false"
        :auto-upload="false"
        :file-list="tempFileList"
        list-type="picture"
        :on-change="handleChange"
        v-if="!tempFileList.length && !fileList.length"
      )
        .file-upload(slot="trigger" v-if="$permission('AB-01003-001')")
          .iconfont.icon-picture
          .file-upload-info 添加图片
      .picture-preview(v-for="item in fileList")
        .picture-preview-bg(:style="item.fileUrl || item.url | filterUrl")
          //- .picture-item-icons
            .handle-btn-icon(@click="deleteFile")
              .iconfont.icon-delete
          el-upload(
            action="#"
            :multiple="false"
            accept="image/png, image/jpeg, image/jpg, image/gif"
            ref="styleUpload"
            :show-file-list="false"
            :auto-upload="false"
            list-type="picture"
            :on-change="handleStyleChange"
          )
            .picture-item-btn(slot="trigger" v-if="$permission('AB-01003-002')") 更换图片
        .picture-preview-bd
          .picture-item-material(v-if="item.type == 2")
            .material-img(:style="{ 'background-image': `url(${item.picImg})` }")
            .material-item-bd
              .material-item-title {{item.materialName}}
              .material-item-info {{item.companyName}}
          .picture-item-link(v-if="item.type == 1")
            .item-link-label 外部链接
            .item-link-bd {{item.url}}
          el-popover(
            popper-class="header-popover"
            placement="bottom-start"
            trigger="click"
            :visible-arrow="false"
          )
            .item-btn-downdrop
              .downdrop-item(@click="changeCate(item, 'fileList', 2)") 单个材料链接
              .downdrop-item(@click="changeLink(item, 'fileList', 1)") 外部链接
            .picture-handle-btn(v-show="(item.url || item.picImg) && $permission('AB-01003-003')" slot="reference") 更换
          .picture-item-handles(v-if="item.type == 3 && $permission('AB-01003-003')")
            .picture-handle-btn(@click="changeCate(item, 'fileList', 2)") 单个材料链接
            .picture-handle-btn(@click="changeLink(item, 'fileList', 1)") 外部链接
  .activity-section
    .header
      .header-title
        span 小轮播图设置
        label 支持png、jpg格式图片，仅能上传5张，建议尺寸为：385*242
      .header-handle
        el-button(name="primary" size="small" @click="saveBanner" v-if="$permission('AB-01003-005')") 应用到平台
    .section-content
      .banners-content
        .banner-item(v-for="item, index in bannerFileList")
          .banner-item-bg(:style="item.fileUrl || item.url | filterUrl")
            .banner-item-tag {{index + 1}}
            .banner-item-icons
              .handle-btn-icon(@click="moveUp(index)" v-if="index !== 0 && $permission('AB-01003-010')")
                .iconfont.icon-up
                label 上移
              .handle-btn-icon(@click="deleteBannerFile(item, index)" v-if="$permission('AB-01003-009')")
                .iconfont.icon-delete
            el-upload(
              action="#"
              :multiple="false"
              accept="image/png, image/jpeg, image/jpg, image/gif"
              ref="styleUpload"
              :show-file-list="false"
              :auto-upload="false"
              list-type="picture"
              :on-change="replaceBannerChange"
            )
              .styles-item-btn(slot="trigger" @click="changeBannerFile(item, index)" v-if="$permission('AB-01003-007')") 更换图片
          .banner-item-bd
            .banner-item-material(v-if="item.type == 2")
              .material-img(:style="{ 'background-image': `url(${item.picImg})` }")
              .material-item-bd
                .material-item-title {{item.materialName}}
                .material-item-info {{item.companyName}}
            .banner-item-link(v-if="item.type == 1")
              .item-link-label 外部链接
              .item-link-bd {{item.url}}
            el-popover(
              popper-class="header-popover"
              placement="top-start"
              trigger="click"
              :visible-arrow="false"
            )
              .banner-item-btn-downdrop
                .downdrop-item(@click="changeCate(item, 'bannerFileList', 2)") 单个材料链接
                .downdrop-item(@click="changeLink(item, 'bannerFileList', 1)") 外部链接
              .banner-item-btn(v-show="(item.url || item.picImg) && $permission('AB-01003-008')" slot="reference") 更换
            .banner-item-handles(v-if="item.type == 3 && $permission('AB-01003-008')")
              .banner-item-btn(@click="changeCate(item, 'bannerFileList', 2)") 单个材料链接
              .banner-item-btn(@click="changeLink(item, 'bannerFileList', 1)") 外部链接
        el-upload(
          action="#"
          :multiple="false"
          accept="image/png, image/jpeg, image/jpg, image/gif"
          ref="bannerAddUpload"
          :show-file-list="false"
          :auto-upload="false"
          :file-list="tempBannerFileList"
          list-type="picture"
          :on-change="handleBannerChange"
        )
          .banner-upload-btn(slot="trigger" v-if="$permission('AB-01003-006')")
            .iconfont.icon-picture
            .file-upload-info 添加图片
  outside-link-modal(:show="showLinkDialog", :item="currentItem" @close="linkHandleClose" @confirm="confirmLink")
  select-material-modal(:show="showMaterialModal" @close="closeMaterialModal" @confirm="confirmMaterialModal")
</template>

<script>
import { FileUpload, getBannerList, addBanner, deleteSlideshow } from 'api'
import outsideLinkModal from '@/components/modal/outsideLinkModal'
import selectMaterialModal from '@/components/modal/selectMaterialModal'
let loading = ''
export default {
  name: 'activity',
  data () {
    return {
      tempFileList: [],
      fileList: [],
      currentItem: {},
      showLinkDialog: false,
      showMaterialModal: false,
      linkType: '',
      fileArrKey: '',
      bannerFileList: [],
      tempBannerFileList: [],
      replaceBannerIndex: ''
    }
  },
  components: {
    outsideLinkModal,
    selectMaterialModal
  },
  methods: {
    async fileUpload (raw) {
      return new Promise(async (resolve, reject) => {
        try {
          let formData = new FormData()
          formData.append('Filedata', raw)
          formData.append("applicationId", 4)
          const { ResultSet } = await this.$axios.post(FileUpload, { formData: formData, isUpload: true }, { headers:{ "Content-Type": "multipart/form-data" } })
          resolve({ ...ResultSet.Result[0] })
        } catch (err) {
          console.log(err)
          reject(err)
        }
      })
    },
    async save () {
      try {
        loading = this.$loading({
          lock: true,
          text: '保存中....',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        let imgs = []
        if (this.tempFileList.length) {
          imgs = await Promise.all(this.tempFileList.map(async (item) => {
            try {
              const file = await this.fileUpload(item.raw)
              return { fileId: file.fileId, tempUrl: item.url }
            } catch (err) {
              console.error('error: ' + JSON.stringify(err))
            }
          }))
        }
        this.fileList.forEach(item => {
          imgs.forEach(row => {
            if (item.fileUrl === row.tempUrl) item.fileId = row.fileId
          })
        })
        await this.$axios.post(addBanner, { showList: this.fileList, classification: 2 })
        this.getList()
        setTimeout(() => {
          loading.close()
        }, 1000)
      } catch (err) {
        setTimeout(() => {
          loading.close()
        }, 1000)
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    deleteFile () {
      this.fileList = []
    },
    changeCate (item, key, type) {
      this.showMaterialModal = true
      this.fileArrKey = key
      this.linkType = type
      this.currentItem = { ...item }
    },
    changeLink (item, key, type) {
      this.showLinkDialog = true
      this.linkType = type
      this.fileArrKey = key
      this.currentItem = { ...item }
    },
    linkHandleClose () {
      this.showLinkDialog = false
      this.currentItem = {}
    },
    confirmLink (data) {
      let index = this[this.fileArrKey].findIndex(item => item.fileUrl === data.fileUrl)
      this[this.fileArrKey][index] = { ...data, type: this.linkType }
      // this[this.fileArrKey][0] = { ...data, type: this.linkType }
      this.showLinkDialog = false
      this.currentItem = {}
    },
    closeMaterialModal () {
      this.showMaterialModal = false
      this.fileArrKey = ''
      this.currentItem = {}
    },
    confirmMaterialModal (data) {
      let index = this[this.fileArrKey].findIndex(item => item.fileUrl === this.currentItem.fileUrl)
      this[this.fileArrKey][index] = { ...this[this.fileArrKey][index], ...data, type: this.linkType }
      // this[this.fileArrKey][0] = { ...this[this.fileArrKey][0], ...data, type: this.linkType }
      this.showMaterialModal = false
      this.currentItem = {}
    },
    handleStyleChange (file, fileList) {
      // file.type = 3
      this.fileList = [{ ...this.fileList[0], fileUrl: file.url }]
      delete this.fileList[0].url
      this.tempFileList = [file]
    },
    handleChange (file, fileList) {
      file.type = 3
      this.fileList = [{ ...file, fileUrl: file.url }]
      delete this.fileList[0].url
      this.tempFileList = [file]
    },
    async getList () {
      try {
        const { ResultSet } = await this.$axios.post(getBannerList, { classification: 2 })
        this.fileList = ResultSet.Result
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    handleBannerChange (file, fileList) {
      if (this.bannerFileList.length >= 5) {
        this.$message.error('小轮播图最多只能上传5张！')
        return
      }
      let temp = { ...file }
      temp.showDrop = false
      temp.type = 3
      temp.fileUrl = file.url
      delete temp.url
      this.bannerFileList.push(temp)
      this.tempBannerFileList = fileList
    },
    changeBannerFile (item, index) {
      this.replaceBannerIndex = index
    },
    replaceBannerChange (file, fileList) {
      this.$set(this.bannerFileList[this.replaceBannerIndex], 'fileUrl', file.url)
      this.tempBannerFileList.push(file)
    },
    moveUp (index) {
      this.bannerFileList.splice(index - 1, 1, ...this.bannerFileList.splice(index, 1 , this.bannerFileList[index - 1]))
    },
    deleteBannerFile (item, index) {
      this.$confirm('是否删除该张照片？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.bannerFileList.splice(index, 1)
        let tempIndex = this.tempBannerFileList.findIndex(row => row.fileUrl === item.fileUrl)
        this.tempBannerFileList.splice(tempIndex, 1)
      })
    },
    async saveBanner () {
      try {
        loading = this.$loading({
          lock: true,
          text: '保存中....',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        let imgs = []
        if (this.tempBannerFileList.length) {
          imgs = await Promise.all(this.tempBannerFileList.map(async (item) => {
            try {
              const file = await this.fileUpload(item.raw)
              return { fileId: file.fileId, tempUrl: item.url }
            } catch (err) {
              console.error('error: ' + JSON.stringify(err))
            }
          }))
        }
        this.bannerFileList.forEach(item => {
          imgs.forEach(row => {
            if (item.fileUrl === row.tempUrl) item.fileId = row.fileId
          })
        })
        await this.$axios.post(addBanner, { showList: this.bannerFileList, classification: 3 })
        this.$message.success('保存成功！')
        this.getList()
        setTimeout(() => {
          loading.close()
        }, 1000)
      } catch (err) {
        setTimeout(() => {
          loading.close()
        }, 1000)
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async getBannerList () {
      try {
        const { ResultSet } = await this.$axios.post(getBannerList, { classification: 3 })
        this.bannerFileList = ResultSet.Result
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.getList()
      vm.getBannerList()
    })
  }
} 
</script>

<style lang="scss">
.picture-upload {
  .el-upload--picture-card {
    width: 100%;
    height: 100%;
    background: transparent;
    border: none !important;
  }
  .header-popover {
    &.el-popover {
      padding: 0 !important;
    }
  }
}
</style>

<style lang="scss" scoped>
.activity-section {
  background: #fff;
  border-radius: 10px;
  width: 100%;
  height: 100%;
  padding: 0 40px;
  margin-bottom: 20px;
}
.header {
  padding: 16px 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #EDEDED;
}
.header-title {
  span {
    display: inline-block;
    font-size: 16px;
    line-height: 24px;
    color: #3E4373;
    margin-right: 16px;
  }
  label {
    font-size: 12px;
    line-height: 20px;
    color: #8B8EAB;
  }
}
.section-content {
  padding: 24px 0;
}
.file-upload {
  width: 996px;
  height: 322px;
  background: #F7F7FD;
  border-radius: 6px;
  .iconfont {
    margin-top: 85px;
    font-size: 40px;
    color: #B2B4C7;
  }
  .file-upload-info {
    margin-top: 8px;
    font-size: 16px;
    line-height: 24px;
    color: #B2B4C7;
  }
}
.picture-preview {
  width: 996px;
  height: 322px;
  background: #F7F7FD;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  .picture-preview-bg {
    position: relative;
    width: 100%;
    height: 242px;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    border-radius: 10px 10px 0 0;
    &:hover {
      .picture-item-icons {
        display: flex;
      }
      .picture-item-btn {
        display: block;
      }
    }
  }
  .picture-preview-bd {
    flex: 1;
    padding: 16px;
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
  }
}
.picture-item-material {
  flex: 1;
  display: flex;
  align-items: center;
  .material-img {
    width: 58px;
    height: 42px;
    margin-right: 8px;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
  }
  .material-item-bd {
    max-width: 326px;
  }
  .material-item-title {
    font-size: 16px;
    line-height: 24px;
    color: #3E4373;
  }
  .material-item-info {
    font-size: 12px;
    line-height: 20px;
    color: #64698F;
    margin-top: 4px;
  }
  .material-item-info,
  .material-item-title {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
.picture-item-tag {
  width: 24px;
  height: 24px;
  line-height: 22px;
  text-align: center;
  font-size: 12px;
  color: #fff;
  background: #8676FF;
  border: 1px solid #FFFFFF;
  border-radius: 6px 0px;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
}
.picture-item-icons {
  position: absolute;
  top: 0;
  right: 0;
  z-index: 2;
  padding: 8px;
  align-items: center;
  display: none;
  .handle-btn-icon {
    margin: 0 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 4px 12px;
    background: rgba(0, 0, 0, 0.5);
    border-radius: 6px;
    color: #fff;
    font-size: 14px;
    cursor: pointer;
    .iconfont {
      font-size: 24px;
    }
    label {
      cursor: pointer;
    }
  }
}
.picture-handle-btn {
  padding: 2px 8px;
  font-size: 14px;
  line-height: 22px;
  background: #FFFFFF;
  color: #FF2E42;
  border-radius: 6px;
  cursor: pointer;
}
.item-link-label {
  font-size: 16px;
  line-height: 24px;
  color: #3E4373;
}
.picture-item-handles {
  display: flex;
  .picture-handle-btn {
    margin-left: 16px;
  }
}
.item-link-bd {
  font-size: 12px;
  line-height: 20px;
  color: #FF2E42;
}
.item-btn-downdrop {
  position: absolute;
  z-index: 1;
  padding: 16px;
  background: #3B3E5C;
  border-radius: 6px;
  .downdrop-item {
    white-space: nowrap;
    color: #FFFFFF;
    font-size: 12px;
    line-height: 20px;
    margin-bottom: 16px;
    cursor: pointer;
    &:last-child {
      margin-bottom: 0;
    }
  }
  &:before {
    content: '';
    position: absolute;
    width: 20px;
    height: 20px;
    border-radius: 6px;
    background: #3B3E5C;
    top: 3px;
    transform: translateY(-50%) rotate(45deg);
  }
}
.picture-item-btn {
  display: none;
  width: 96px;
  height: 32px;
  position: absolute;
  left: 8px;
  bottom: 8px;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 6px;
  color: #fff;
  font-size: 14px;
  line-height: 32px;
  text-align: center;
  cursor: pointer;
}
.banners-content {
  display: flex;
  flex-wrap: wrap;
}
.banner-upload-btn {
  width: 385px;
  height: 322px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  background: #F7F7FD;
  border-radius: 6px;
  margin-right: 40px;
  margin-bottom: 24px;
  .iconfont {
    font-size: 40px;
    color: #B2B4C7;
  }
  .file-upload-info {
    margin-top: 8px;
    font-size: 16px;
    line-height: 24px;
    color: #B2B4C7;
  }
}
.banner-item {
  width: 385px;
  height: 322px;
  display: flex;
  flex-direction: column;
  background: #F7F7FD;
  border-radius: 6px;
  margin-right: 40px;
  margin-bottom: 24px;
  .banner-item-bg {
    position: relative;
    width: 100%;
    height: 242px;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    border-radius: 6px 6px 0 0;
    &:hover {
      .banner-item-icons {
        display: flex;
      }
      .styles-item-btn {
        display: block;
      }
    }
    .banner-item-tag {
      width: 24px;
      height: 24px;
      line-height: 22px;
      text-align: center;
      font-size: 12px;
      color: #fff;
      background: #8676FF;
      border: 1px solid #FFFFFF;
      border-radius: 6px 0px;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 2;
    }
    .banner-item-icons {
      position: absolute;
      top: 0;
      right: 0;
      z-index: 2;
      padding: 8px;
      align-items: center;
      display: none;
      .handle-btn-icon {
        margin: 0 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 4px 12px;
        background: rgba(0, 0, 0, 0.5);
        border-radius: 6px;
        color: #fff;
        font-size: 14px;
        cursor: pointer;
        .iconfont {
          font-size: 24px;
        }
        label {
          cursor: pointer;
        }
      }
    }
    .styles-item-btn {
      display: none;
      width: 96px;
      height: 32px;
      position: absolute;
      left: 8px;
      bottom: 8px;
      background: rgba(0, 0, 0, 0.5);
      border-radius: 6px;
      color: #fff;
      font-size: 14px;
      line-height: 32px;
      text-align: center;
      cursor: pointer;
    }
  }
}
.banner-item-bd {
  flex: 1;
  padding: 16px;
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  .banner-item-material {
    flex: 1;
    display: flex;
    align-items: center;
    .material-img {
      width: 58px;
      height: 42px;
      margin-right: 8px;
      background-position: center;
      background-repeat: no-repeat;
      background-size: cover;
    }
    .material-item-bd {
      max-width: 326px;
    }
    .material-item-title {
      font-size: 16px;
      line-height: 24px;
      color: #3E4373;
    }
    .material-item-info {
      font-size: 12px;
      line-height: 20px;
      color: #64698F;
      margin-top: 4px;
    }
    .material-item-info,
    .material-item-title {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
  .banner-item-handles {
    display: flex;
    .banner-item-btn {
      margin-left: 16px;
    }
  }
  .banner-item-btn {
    padding: 2px 8px;
    font-size: 14px;
    line-height: 22px;
    background: #FFFFFF;
    color: #FF2E42;
    border-radius: 6px;
    cursor: pointer;
  }
}
.banner-item-btn-downdrop {
  position: absolute;
  z-index: 1;
  padding: 16px;
  background: #3B3E5C;
  border-radius: 6px;
  transform: translateY(-100%);
  .downdrop-item {
    white-space: nowrap;
    color: #FFFFFF;
    font-size: 12px;
    line-height: 20px;
    margin-bottom: 16px;
    cursor: pointer;
    &:last-child {
      margin-bottom: 0;
    }
  }
  &:before {
    content: '';
    position: absolute;
    width: 20px;
    height: 20px;
    border-radius: 6px;
    background: #3B3E5C;
    bottom: 3px;
    transform: translateY(50%) rotate(45deg);
  }
}
</style>
